//
//  UIButton+CXAdd.m
//  XiMaFM
//
//  Created by hcios on 2017/9/2.
//  Copyright © 2017年 hcios. All rights reserved.
//

#import "UIButton+CXAdd.h"

@implementation UIButton (CXAdd)

// 设置button的titleLabel和imageView的布局样式，及间距
- (void)cx_layoutButtonWithEdgeInsetsStyle:(CX_ButtonEdgeInsetsStyle)cx_style
                           imageTitleSpace:(CGFloat)cx_space {
    
    //    [self sizeToFit];
    
    // 得到imageView和titleLabel的宽、高
    
    CGFloat cx_imageWidth  = 0.0;
    CGFloat cx_imageHeight = 0.0;
    
    CGFloat cx_labelWidth  = 0.0;
    CGFloat cx_labelHeight = 0.0;
    
    if (self.currentImage) {
        cx_imageWidth  = self.imageView.bounds.size.width;
        cx_imageHeight = self.imageView.bounds.size.height;
    }
    
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        cx_labelWidth  = self.titleLabel.intrinsicContentSize.width;
        cx_labelHeight = self.titleLabel.intrinsicContentSize.height;
    } else {
        cx_labelWidth  = self.titleLabel.frame.size.width;
        cx_labelHeight = self.titleLabel.frame.size.height;
    }
    
    UIEdgeInsets cx_imageEdgeInsets = UIEdgeInsetsZero;
    UIEdgeInsets cx_labelEdgeInsets = UIEdgeInsetsZero;
    
    // 根据cx_style和cx_space得到cx_imageEdgeInsets和cx_labelEdgeInsets的值
    switch (cx_style) {
        case CX_ButtonEdgeInsetsStyleTop:
            cx_imageEdgeInsets = UIEdgeInsetsMake(-cx_labelHeight-cx_space/2.0, 0, 0, -cx_labelWidth);
            cx_labelEdgeInsets = UIEdgeInsetsMake(0, -cx_imageWidth, -cx_imageHeight-cx_space/2.0, 0);
            break;
        case CX_ButtonEdgeInsetsStyleLeft:
            cx_imageEdgeInsets = UIEdgeInsetsMake(0, -cx_space/2.0, 0, cx_space/2.0);
            cx_labelEdgeInsets = UIEdgeInsetsMake(0, cx_space/2.0, 0, -cx_space/2.0);
            break;
        case CX_ButtonEdgeInsetsStyleBottom:
            cx_imageEdgeInsets = UIEdgeInsetsMake(0, 0, -cx_labelHeight-cx_space/2.0, -cx_labelWidth);
            cx_labelEdgeInsets = UIEdgeInsetsMake(-cx_imageHeight-cx_space/2.0, -cx_imageWidth, 0, 0);
            break;
        case CX_ButtonEdgeInsetsStyleRight:
            cx_imageEdgeInsets = UIEdgeInsetsMake(0, cx_labelWidth+cx_space/2.0, 0, -cx_labelWidth-cx_space/2.0);
            cx_labelEdgeInsets = UIEdgeInsetsMake(0, -cx_imageWidth-cx_space/2.0, 0, cx_imageWidth+cx_space/2.0);
            break;
        default:
            break;
    }
    self.titleEdgeInsets = cx_labelEdgeInsets;
    self.imageEdgeInsets = cx_imageEdgeInsets;
    //    [self sizeToFit];
}



@end
